package com.leff.cards.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.leff.cards.R;
import com.leff.cards.data.AppState;
import com.leff.cards.data.CompositeResponseCard;
import com.leff.cards.data.Group;
import com.leff.cards.data.QueryCard;
import com.leff.cards.data.ResponseCard;
import com.leff.cards.ui.util.CardListAdapter;
import com.leff.cards.util.Secrets;
import com.leff.cards.util.FacebookSession;
import com.leff.cards.util.Settings;
import com.leff.cards.web.QueryDispatcher;
import com.leff.cards.web.requests.SelectCardRequest;
import com.leff.cards.web.requests.SubmitRequest;

public class QueryCardViewFragment extends SherlockFragment implements Secrets, OnItemClickListener {
	
	private Group mGroup;
	private QueryCard mCard;
	
	private TextView mCardText;
	private CardListAdapter mAdapter;
	private int mActiveResponse;
	
	private TextView mVoterText;
	private TextView mNoResponsesText;
	
	private boolean mIsVoter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mGroup = AppState.get().getActiveGroup();
		mCard = mGroup.activeCard;
		mActiveResponse = 0;
		
		mIsVoter = mGroup.isVoter;
		
		this.setHasOptionsMenu(true);
		
		mAdapter = new CardListAdapter(getActivity(), mGroup.responseCards, mIsVoter ? 1 : mCard.getRequiredNumberOfInputs());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		View V = inflater.inflate(R.layout.active_query_card, null);
		
		mCardText = (TextView)V.findViewById(R.id.card_text);
		
		ListView responseList = (ListView)V.findViewById(R.id.card_list);
		responseList.setAdapter(mAdapter);
		responseList.setOnItemClickListener(this);
		
		mVoterText = (TextView)V.findViewById(R.id.voter_text);
		mNoResponsesText = (TextView)V.findViewById(R.id.no_responses_text);
		
		refreshUI();
		
		return V;
	}
	
	private void refreshUI() {

		mCardText.setText(mCard.getTextWithResponses());
		getActivity().supportInvalidateOptionsMenu();

		mVoterText.setVisibility(mIsVoter ? View.VISIBLE : View.GONE);
		mNoResponsesText.setVisibility((mIsVoter && mAdapter.getCount() < 1) ? View.VISIBLE : View.GONE);
	}
	
	private void reset() {
		mCard.reset();
		mActiveResponse = 0;
		mAdapter.resetSelections();
		refreshUI();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		case R.id.menu_reset:
			reset();
			return true;
			
		case R.id.menu_submit:
			Group G = AppState.get().getActiveGroup();
			long userId = AppState.get().getUser().id;
			
			if(mIsVoter) {
				
				if(Settings.getPostToFacebook() && Settings.getVotePostPreference() != Settings.FB_POST_NEVER) {
					
					if(Settings.getVotePostPreference() == Settings.FB_POST_ALWAYS) {
						FacebookSession.getSession().postCardSelection(mCard);
						doSelect();
					}
					else {
						showFacebookPostPrompt();
					}
				}
				else {
					doSelect();
				}
			} 
			else {
				new QueryDispatcher(new SubmitRequest(G.id, userId, mCard.getResponses())).execute();
			}

			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	
	private void doSelect() {
		Group G = AppState.get().getActiveGroup();
		
		new QueryDispatcher(new SelectCardRequest(G.id, mCard.getResponses())).execute();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		
		inflater.inflate(R.menu.query_card_menu, menu);
		
		MenuItem submit = menu.findItem(R.id.menu_submit);
		submit.setVisible(mCard.isCompleted());
		
		if(mIsVoter || !mCard.hasResponses()) {
			menu.removeItem(R.id.menu_reset);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View V, int pos, long id) {
		
		int intId = (int)id;

		if(!mAdapter.select(mActiveResponse, intId)) {
			return;
		}
		
		if(mIsVoter) {
			CompositeResponseCard crc = (CompositeResponseCard)mAdapter.getItem(pos);
			
			mCard.setResponses(crc);
		}
		else {
			ResponseCard response = (ResponseCard)mAdapter.getItem(pos);
			
			mCard.setResponse(mActiveResponse, response);
			mActiveResponse = (mActiveResponse + 1) % mCard.getRequiredNumberOfInputs();
		}
		
		refreshUI();
	}
	
	private void showFacebookPostPrompt() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		
		builder.setTitle(R.string.facebook_prompt_title);
		builder.setMessage(R.string.facebook_vote_message);
		
		builder.setPositiveButton(R.string.share, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				FacebookSession.getSession().postCardSelection(mCard);
				doSelect();
			}
		});
		builder.setNegativeButton(R.string.no_thanks, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				doSelect();
			}
		});
		
		builder.create().show();
	}
}
